import axios from 'axios'
// import store from '@/store/store'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.SERVICE_BASE_URL, // url = base url + request url    // withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    console.log(store)
    // store.state.token = 'eY3NnVJMozeqqpSHCQz/Q+h4RSc/sjEEIQCxBwcHLsbdTMNOcySIinOTMyeRm02Hcha8QY3N+m4NmkqQeFg8lladdbUpyVVtryiq4P621IxcviPIpLoOdf2jI2DZtmbwcCdEBi288USnSGQpZFvdt/lhjbzDge+R+kgkbUQPskYEzk6cSNrTiduOpkNpNqH3V3m15g+1M9hZUkKhepVbH4dq+2BmgpMbXV0bRbqaK/EwKbTAT2sO6+KHIj48N+QB7imGTIJXcrcIqZGuTJ1IT7gac/caEidi+oOhlrhyeN/S3CCbzNoJxYom/LFUTARbXh8s8RZBFvsy+8txP0HUxQ=='
    // do something before request is sent
    // console.log(store.token)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
      // console.log('----token', getToken())
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if (typeof response.data.code === 'undefined') {
      return response.data.data
    } else if (response.data.code === 0) {
      Message({
        message: response.data.message,
        type: 'success',
        duration: 3 * 1000
      })
      return response.data.data
    } else if (response.data.code === 301) {
      router.replace('/login')
      Message({
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(response.data.message)
    }
  },
  error => {
    // 请求失败，统一处理
    // console.log('err' + error) // for debug
    Message({
      message: '系统错误',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
